﻿using AutoMapper;
using Decoration.Api.Comm;
using Decoration.IService;
using Decoration.Models;
using Decoration.Models.DTO;
using Decoration.Models.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Decoration.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MenuInfoController : ControllerBase
    {
        IMenuInfoService svc;
        public MenuInfoController(IMenuInfoService svc)
        {
            this.svc = svc;
        }
        /// <summary>
        /// 一级菜单查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("menuone")]
        public Result MenuOne()
        {
            //var sql = @" select * from Base_MenuInfo where PId=0 and Status=1 order by MenuOrder ";

            //var info = svc.Query<Base_MenuInfo>(sql);

            var SQl = svc.Query(o => o.PId == 0 && o.Status == 1).OrderByDescending(o => o.MenuOrder);
            return new Result() { code = 1, msg = "成功", data = SQl };
        }
        /// <summary>
        /// 根据用户Id查询菜单
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("getmenubyuserid")]
        public Result GetMenuByUserId(int UserId)
        {
            var sql = @" select distinct mi.* from Base_UserRoles ur
                    inner join Base_RoleMenus rm on ur.RoleId=rm.RoleId
                    inner join Base_MenuInfos mi on rm.MenuId=mi.Id
                    where UserId=1 and mi.Status=1 and mi.isshow=1
                    ";
            var info = svc.Query<Base_MenuInfo>(sql, new { UserId });
            return new Result() { code = 1, msg = "成功", data = info };
        }
        [Route("mymenus")]
        [HttpGet]
        [MyAuthorize]
        /// <summary>
        /// 获取登录后用户能看到的菜单数据
        /// </summary>
        /// <returns></returns>
        public Result GetUserMenus()
        {
            //取路由数据
            var auth = RouteData.Values;
            AuthInfo obj = new AuthInfo();
            if (auth.Keys.Contains("auth"))
                obj = auth["auth"] as AuthInfo;

            var menus = svc.GetMenuByUserId(obj.UserId);
            var one = svc.MenuOne();

            List<MenuDto> list = new List<MenuDto>();
            //构造一级菜单
            foreach (var item in one)
            {
                var menu = new MenuDto() { Id = item.Id, MenuName = item.MenuName, MenuUrl = item.MenuUrl, MenuIcon = item.MenuIcon };
                //构建二级菜单
                var children = menus.Where(o => o.PId == item.Id).ToList();
                var cs = new List<MenuDto>();
                foreach (var c in children)
                {
                    cs.Add(new MenuDto() { Id = c.Id, MenuName = c.MenuName, MenuUrl = c.MenuUrl, MenuIcon = c.MenuIcon });

                }
                menu.Children = cs;
                //如果没有子菜单，那么一级菜单不显示
                if (cs.Count > 0)
                {
                    list.Add(menu);
                }

            }

            var result = new Result() { code = 1, msg = "成功", data = list };
            return result;
        }
        [Route("tree")]
        [HttpGet]
        public Result GetTree()
        {
            var l = svc.Query(o => o.Status == 1 && o.IsShow == 1).ToList();

            var sql = @" select * from Base_MenuInfo where PId=0 and Status=1 order by MenuOrder ";
            var one = svc.Query<Base_MenuInfo>(sql);
            List<ElementTree> list = new List<ElementTree>();
            //构造一级菜单
            foreach (var item in one)
            {
                var menu = new ElementTree() { id = item.Id, label = item.MenuName, Icon = item.MenuIcon };
                //构建二级菜单
                var children = l.Where(o => o.PId == item.Id).ToList();
                var cs = new List<ElementTree>();
                foreach (var c in children)
                {
                    cs.Add(new ElementTree() { id = c.Id, label = c.MenuName, Icon = c.MenuIcon });

                }
                menu.children = cs;
                if (cs.Count > 0)
                {
                    list.Add(menu);
                }

            }

            var result = new Result() { code = 1, msg = "成功", data = list };

            return result;
        }
        [HttpGet]
        [HttpGet("{id}")]
        public Result Get(int id)
        {
            var info = svc.Query(o => o.Id == id).FirstOrDefault();

            return new Result() { code = 1, msg = "成功", data = info };
        }
        // POST api/<FilmsController>
        [HttpPost]
        public Result Post(Base_MenuInfo bo)
        {
            bo.Status = 1;
            bo.CreateTime = DateTime.Now;
            var res = svc.Add(bo);
            if (res)
            {
                return new Result() { code = 1, msg = "成功" };
            }
            else
            {
                return new Result() { code = -1, msg = "失败" };
            }
        }
        [HttpDelete]
        public Result Delele(int id)
        {
            var data = svc.Get(o => o.Id == id);
            if (data != null)
            {
                data.Status = 0;
                data.IsShow = 0;
                //逻辑删除
                //var entity = mapper.Map<Base_MenuInfo>(data);
                var res = svc.Update(data);
                //物理删除
                //bll.Delete(info);
                if (res)
                {
                    return new Result() { code = 1, msg = "成功" };
                }
                else
                {
                    return new Result() { code = -1, msg = "删除失败" };
                }
            }
            else
            {
                return new Result() { code = -1, msg = "你要删除的数据不存在" };
            }
        }
        [HttpPut]
        public Result Put(Base_MenuInfo bo)
        {

            var info = svc.Get(o => o.Id == bo.Id);
            if (info != null)
            {
                info.MenuName = bo.MenuName;
                info.PId = bo.PId;
                info.MenuIcon = bo.MenuIcon;
                info.Status = bo.Status;
                info.MenuUrl = bo.MenuUrl;
                info.MenuOrder = bo.MenuOrder;
                info.IsShow = bo.IsShow;
                info.CreateTime = DateTime.Now;
                svc.Update(info);
                return new Result() { code = 1, msg = "成功" };
            }
            else
            {
                return new Result() { code = -1, msg = "你要修改的数据不存在" };
            }
        }

        //分页查询
        [HttpGet]
        [Route("Query")]
        public PagedResult<Base_MenuInfo> Query(string? MenuName, int pagesize = 10, int pageindex = 1)
        {
            var data = svc.Query(o => true);
            if (!string.IsNullOrEmpty(MenuName))
            {
                data = data.Where(o => o.MenuName.Contains(MenuName));
            }

            int total = data.Count();
            data = data.OrderByDescending(o => o.CreateTime).Skip(pagesize * (pageindex - 1)).Take(pagesize);

            return new PagedResult<Base_MenuInfo>() { code = 1, msg = "成功", data = data, total = total };
        }

    }

}
